<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-operator" v-action:create_roles>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="customer" v-action:give_role_to_user slot-scope="text, record">
          <template>
            <a @click="routeAdmin(record)">{{ text.length }}</a>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="addAdmin(record)" v-action:give_role_to_user >添加管理员</a>
            <a-divider type="vertical"/>
            <a @click="handleSub(record)" v-action:give_permission_to_role >权限配置</a>
            <a-divider type="vertical"/>
            <a @click="handleEdit(record)" v-action:edit_roles >修改</a>
            <a-divider type="vertical"/>
            <a @click="handleRemove(record)" v-action:del_roles >删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
        :auth="auth"
        :permissionList="permissionList"
      />
      <add-admin-list
        ref="adminList"
        :visible="visibleA"
        :loading="confirmLoadingA"
        :model="mdl"
        @cancel="handleCancelA"
        @ok="handleOkA"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { createRoles, rolesList, permissionList, givePermission2Role, giveRole2User, editRoles, delRoles, rolePermissionList } from '@/api'
import CreateForm from './modules/CreateContentForm'
import AddAdminList from './modules/AddAdminList'
import { mapGetters } from 'vuex'

const statusMap = {
  0: {
    status: 'default',
    text: '撤回'
  },
  1: {
    status: 'success',
    text: '正常'
  }
}

export default {
  components: {
    STable,
    CreateForm,
    AddAdminList
  },
  data () {
    return {
      columns: [
        {
          title: '角色ID',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '角色名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '350px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: null,
      visibleA: false,
      confirmLoadingA: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      permissionList: [],
      permissionBList: [],
      permissionCList: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await rolesList({ ...params })
        const result = {
          pageNo: res.current_page || 1,
          totalPage: res.last_page || 1,
          data: res.list,
          pageSize: 10,
          totalCount: res.total || res.list.length
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      auth: false,
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  created () {
    permissionList({ type: 'all' }).then(res => {
      this.permissionList = res.list
    })
    // 由于后端能力不够，所以要前端再请求一遍接口，呵呵^v^
    permissionList().then(res => {
      this.permissionBList = res.list.filter(v => v.level == 3)
      this.permissionCList = res.list.filter(v => v.level == 2)
    })
    this.$nextTick(() => {
      // 别问，用就完了
      const res = this.roles.permissions.filter(v => v?.permissionId == 'system.roles_list' && v?.actionEntitySet?.find(u => u?.action?.includes('give_role_to_user')))
      if (res.length > 0) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: '管理',
          dataIndex: 'customer',
          align: 'center',
          scopedSlots: { customRender: 'customer' }
        })
      }
    })
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    },
    ...mapGetters(['roles'])
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    async handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    async handleSub (record) {
      this.$refs.table.localLoading = true
      const res = await rolePermissionList({ role_id: record.id }).finally(() => (this.$refs.table.localLoading = false))
      let arr = []
      if (res) {
        const readyAData = res.filter(u => u.level == 3)
        const readyBData = res.filter(u => u.level == 2)
        const readyCData = res.filter(u => u.level == 1)
        readyCData.forEach(v => {
           const A = readyBData.find(u => u.pid == v.id)
           // 按照这个系统一般来讲不会走else, 所以你只需要关心if里面的逻辑就够了， 这里同样是因为后端的无能所以要解析
           if (A && A.pid) {
             readyBData.forEach(s => {
               const B = readyAData.find(k => k.pid == s.id)
               if (!B) arr.push(s.id)
             })
           } else {
             arr.push(v.id)
           }
        })
        // 必然会取第三级，所以直接赋值
        arr = Array.from(new Set([ ...arr, ...readyAData.map(v => v.id) ]))
      }
      this.mdl = {
        ...record,
        permission_ids: arr
      }
      this.okHidden = true
      this.visible = true
    },
    routeAdmin (record) {
      this.$router.push({
        path: '/admin/admin/setting',
        query: { '#': encodeURIComponent(JSON.stringify({ role_id: record.id })) }
      })
    },
    addAdmin (record) {
      this.mdl = record
      this.visibleA = true
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res && res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (this.mdl && this.mdl.id > 0) {
            values.role_id = values.id
            if (this.okHidden) {
              // 由于后端能力不够，所以由前端来处理数据，呵呵^v^
              try {
                const formatData = (list, levelList) => {
                  const arr = []
                  list.map(v => {
                    const permissionId = levelList.find(u => u.id == v)
                    // 如果有三级的话放入数组
                    if (permissionId && permissionId.pid) {
                      arr.push(permissionId.pid)
                    }
                  })
                  return Array.from(new Set(arr))
                }
                const ids = [ ...values.permission_ids ]
                // 查2级 查3级 查2和3级，🤮
                const levelBList = formatData(ids, this.permissionBList)
                const levelABList = formatData(ids, this.permissionCList)
                const levelAList = formatData([ ...levelBList, ...levelABList ], this.permissionCList)
                values.permission_ids = [ ...values.permission_ids, ...levelBList, ...levelAList, ...levelABList ]
                // 写了一大堆垃圾，真他妈恶心
              } catch (err) {
                console.warn(err)
                // 尝试解析失败后重载
                location.reload()
              }
              givePermission2Role(values)
                .then(res => success(res, '配置成功'))
                .finally(final)
            } else {
              editRoles(values)
                .then(res => success(res, '修改成功'))
                .finally(final)
            }
          } else {
            createRoles(values)
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该角色吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method({ role_id: record.id })
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    async handleRemove (record) {
      this.openModal(delRoles, record, '删除')
    },
    handleCancelA () {
      this.visibleA = false
    },
    async handleOkA (params = {}) {
        if (params?.length < 1) return this.$message.warn('请至少选择一条')
        this.confirmLoadingA = true
        const success = () => {
          this.$message.info('添加成功')
          this.$refs.table.refresh()
          this.visibleA = false
        }
        const final = () => {
          this.confirmLoadingA = false
        }
        const res = await giveRole2User({
          customer_ids: params,
          role_id: this.mdl.id
        }).finally(final)
        if (res && res.is_ok == 'Y') success()
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
